
from app import app, request, db
from app.common.common import res_json, base_url,res_sucss,res_msg,random_str,random_num
import time
from app.models.shop_list import *
from app.models.cusotmer import *
from app.controller.token import certify_token,generate_token,login_required
from app.static.json.china_address_v4 import chaina_add
import threading
def change_order_state():
    print('执行修改订单方法')
    global timer  # 定义变量
    timer = threading.Timer(5, change_order_state)
    order_list = Order_list.query.filter_by(orderStatus=1).all()
    date_now = datetime.now()
    for order_item in order_list:
        if (date_now - order_item.createTime).seconds > 1800:
            app.logger.info('订单超时30分钟，修改订单状态 orderNo: %s' % (order_item.orderNo))
            order_item.orderStatus = 4
            order_item.isClosed = 1
            order_item.isPay = 0
            db.session.commit()
    timer.start()
    return 'success'

# timer = threading.Timer(5,change_order_state)  #首次启动
# timer.start()

#顾客注册
@app.route('/api/v1/staff/register',methods=['POST'])
def sataff_register():
    username = request.form.get('username')
    password = request.form.get('password')
    user = Staff.query.filter_by(userId=username).first()
    if user:
        return res_msg('201','用户已存在，请直接登录')
    staff_item = Staff(userId=username)
    staff_item.hash_password(password)
    db.session.add(staff_item)
    db.session.commit()
    return res_msg(200,'注册成功')

#顾客登录
@app.route('/api/v1/staff/login',methods=['POST'])
def staff_login():
    username = request.form.get('username')
    password = request.form.get('password')
    obj = Staff.query.filter_by(userId=username).first()
    if not obj:
        return res_json(201,'','未找到该用户')
    if obj.verify_password(password):
        token = generate_token(username)
        return res_json(200,{'token':token,'user':username},'登录成功')
    else:
        return res_json(201,'','密码错误')

#返回分类菜单及商品api
@app.route('/api/v1/staff/get_menu_data',methods=['POST'])
def get_menu_data():
    user = request.form.get('user') or '13940217916'
    classs_obj =  Goods_class.query.filter_by(shop_id=user).all()
    data_arr = []
    for item in classs_obj:
        data_arr.append({
            'id':item.id,
            'name':item.name,
            'type':item.type,
            'foods':[]
        })
    for item in data_arr:
        goods = Goods.query.filter_by(class_id=item['id']).all()
        for g in goods:
            item['foods'].append({
                'id':g.id,
                'name':g.name,
                'icon':base_url + g.Icon,
                'oldPrice':g.oldPrice / 100,
                'price':g.price / 100,
                'description':g.description,
                'sellCount':g.sellCount,
                'moneny_type':'yuan'
            })
    return res_json(200,data_arr,'成功')

#获取商户信息接口
@app.route('/api/v1/staff/get_shopinfo',methods=['POST'],endpoint='staff_get_shopinfo')
@login_required
def staff_get_shopinfo(users):
    user = request.form.get('shop_id') or '13940217916'
    info_item = Shop_info.query.filter_by(shop_id=user).first()
    news =len(Order_list.query.filter_by(staffId=users,orderStatus=2).all()) 
    if(info_item=='' or info_item==None):
        return res_msg('201','无此店铺')
    res_datas={
        'avatar':base_url + info_item.avatar,
        'bulletin':info_item.bulletin,
        'deliveryprice':info_item.deliveryPrice /100,
        'minprice':info_item.minPrice / 100,
        'name':info_item.name,
        'sellCount':info_item.sellCount,
        'deliveryTime':info_item.deliveryTime,
        'news':news
    }
    return res_json('200',res_datas,'操作成功')

#设置全部地址为非默认
def setAdress_default(userId):
    s = Adress_list.query.filter_by(userId = userId).all()
    for item in s:
        item.isDefault = 0
    db.session.commit()
    return 'ok'

#设置默认地址接口
@app.route('/api/v1/setAdressDefault',methods=['POST'],endpoint='setAdressDefault')
@login_required
def setAdressDefault(usrname):
    adress_id = request.form.get('adress_id')
    userId = usrname
    if usrname:
        setAdress_default(usrname)
    if adress_id:
        add_id = Adress_list.query.filter_by(addressId = adress_id).first()
        add_id.isDefault = 1
        db.session.commit()
    return res_sucss()

#地址列表
@app.route('/api/v1/staff/adress_list',methods=['POST'],endpoint='adress_list')
@login_required
def adress_list(user):
    add_list = Adress_list.query.filter_by(userId=user).order_by(Adress_list.createTime.desc()).all()
    list_arr = []
    for item in add_list:
        list_arr.append({
            'addressId':item.addressId,
            'userName':item.userName,
            'userPhone':item.userPhone,
            'areaIdPath':item.areaIdPath,
            'userAddress':item.userAddress,
            'isDefault':item.isDefault,
            'userId':item.userId
        })
    return res_json(200,list_arr,'成功！')

#新增/修改 地址
@app.route('/api/v1/staff/nwe_adress',methods=['POST'],endpoint='nwe_adress')
@login_required
def nwe_adress(user):
    addressId = request.form.get('addressId')
    userName = request.form.get('userName')
    userPhone =  request.form.get('userPhone')
    areaIdPath =  request.form.get('areaIdPath')
    areaId =  request.form.get('areaId')
    userAddress =  request.form.get('userAddress')
    
    if userName == None or userPhone == None or areaIdPath == None or areaId == None or userAddress == None:
        return res_msg(201,'参数错误')
    if addressId == None or addressId == '':
        setAdress_default(user)
        Adress_item = Adress_list(userName=userName,userPhone=userPhone,addressId = random_str(32),areaIdPath=areaIdPath,areaId=areaId,userAddress=userAddress,userId=user)
        db.session.add(Adress_item)
        db.session.commit()
        return res_sucss()
    else:
        add_item = Adress_list.query.filter_by(addressId = addressId).first()
        add_item.userName = userName
        add_item.userPhone = userPhone
        add_item.areaIdPath = areaIdPath
        add_item.areaId = areaId
        add_item.userAddress = userAddress
        db.session.commit()
        return res_sucss()


#删除地址
@app.route('/api/v1/staff/del_adress',methods=['POST'],endpoint='del_adress')
@login_required
def del_adress(user):
    addressId = request.form.get('addressId') or None
    if not addressId == None:
        add_item = Adress_list.query.filter_by(addressId = addressId).first()
        db.session.delete(add_item)
        db.session.commit()
        return res_sucss()

@app.route('/api/v1/test_api',methods=['POST'])
def test_api():
    order_goods = request.form.to_dict()
    print(order_goods['password'])
    return 'suuccess'

#创建订单接口
@app.route('/api/v1/staff/creat_order',methods=['POST'],endpoint='creat_order')
@login_required
def creat_order(user):
    orderNo = 'RN'+ random_num(32)
    goodsMoney = request.form.get('goodsMoney')
    realTotalMoney = request.form.get('realTotalMoney')
    payType = request.form.get('payType')
    payFrom = request.form.get('payFrom')
    userName = request.form.get('userName') 
    userAddress = request.form.get('userAddress')
    userPhone = request.form.get('userPhone')
    orderRemarks = request.form.get('orderRemarks')
    areaIdPath = request.form.get('areaIdPath')
    shopId = request.form.get('shopId')
    order_goods = request.form.to_dict('goods_arr')
    goods_num = request.form.get('goods_num')
    staffId = request.form.get('staff_id')
    if orderNo == None or goodsMoney == None or realTotalMoney == None or payType == None or payFrom == None or \
    userName == None or userAddress == None or userPhone == None or orderRemarks == None or areaIdPath == None or \
    shopId == None or staffId == None:
        return res_msg(201,'参数错误')
    orderStatus = 0
    if payType == 0 or payType == '0':
        orderStatus = 1
    for item in range(int(goods_num)):
        order_good = Order_goods(good_id=order_goods['goods_arr[%s][id]' % (item)],good_price=order_goods['goods_arr[%s][price]' % (item)],count=order_goods['goods_arr[%s][count]' % (item)],orderNo=orderNo, \
        good_name=order_goods['goods_arr[%s][name]' % (item)],Icon=order_goods['goods_arr[%s][icon]' % (item)])
        db.session.add(order_good)
    Save_item = Order_list(orderNo=orderNo,goodsMoney=goodsMoney,realTotalMoney=realTotalMoney,payType=payType,payFrom=payFrom,userName=userName,\
    userAddress=userAddress,userPhone=userPhone,orderRemarks=orderRemarks,orderStatus=orderStatus,areaIdPath=areaIdPath,shopId=shopId,staffId=staffId)
    db.session.add(Save_item)
    db.session.commit()
    return res_sucss()

#订单列表接口
@app.route('/api/v1/staff/order_list',methods=['POST'],endpoint='order_list')
@login_required
def order_list_func(user):
    try:
        order_state = request.form.get('order_state') or None
        staff_id = request.form.get('staff_id') or None
        shop_id = request.form.get('shop_id') or None
        order_list = ''
        #顾客订单
        if not staff_id == None:
            if order_state == None:
                return res_msg(201,'参数错误')
            elif order_state == '5':
                order_list = Order_list.query.filter_by(staffId=staff_id).order_by(Order_list.createTime.desc()).all()
            else:
                order_list = Order_list.query.filter_by(orderStatus=order_state,staffId=staff_id).order_by(Order_list.createTime.desc()).all()
        #商户订单
        elif not shop_id == None:
            if order_state == None:
                return res_msg(201,'参数错误')
            elif order_state == '5':
                order_list = Order_list.query.order_by(Order_list.createTime.desc()).all()
            else:
                order_list = Order_list.query.filter_by(orderStatus=order_state,shopId=shop_id).order_by(Order_list.createTime.desc()).all()

        order_arr = []
        for order_item in order_list:
            shopItem = Shop_info.query.filter_by(shop_id=order_item.shopId).first()
            order_arr.append({
                'orderNo':order_item.orderNo,
                'orderStatus': order_item.orderStatus,
                'goodsMoney': order_item.goodsMoney,
                'realTotalMoney': order_item.realTotalMoney,
                'shopId': order_item.shopId,
                'avatar':base_url + shopItem.avatar,
                'name':shopItem.name,
                'createTime':str(order_item.createTime)
            })
    except:
        pass
    return res_json(200,order_arr,'success')

#地址编码查询接口
def search_areacode(areacode):
    if not areacode == None:
        areacode_arr = areacode.split('_')
        result = []
        for it in areacode_arr:
            result.append(ChinaAdress.query.filter_by(value=it).first().name)
        return result

#订单详情接口
@app.route('/api/v1/staff/order_details',methods=['POST'],endpoint='order_details')
@login_required
def order_details(user):
    orderNo = request.form.get('orderNo') or None
    print('订单详情 打印订单号 %s' % (orderNo))
    if orderNo == None or orderNo == '':
        return res_msg(201,'参数错误')
    order_detail = Order_list.query.filter_by(orderNo=orderNo).first()
    shopItem = Shop_info.query.filter_by(shop_id=order_detail.shopId ).first()
    order_detail_arr = {
        'orderNo':order_detail.orderNo,
        'orderStatus':order_detail.orderStatus,
        'realTotalMoney':order_detail.realTotalMoney,
        'userName':order_detail.userName,
        'areaIdPath':search_areacode(order_detail.areaIdPath),
        'userAddress':order_detail.userAddress,
        'userPhone':order_detail.userPhone,
        'orderRemarks':order_detail.orderRemarks,
        'order_goods':[],
        'shop_name':shopItem.name,
        'shop_phone':shopItem.shop_id
    }
    
    for item in  order_detail.orderGoods:
        order_detail_arr['order_goods'].append({
            'good_id':item.good_id,
            'count':item.count,
            'good_name':item.good_name,
            'Icon':item.Icon,
            'price':item.good_price
        })
    return res_json(200,order_detail_arr,'success')

#取消订单接口
@app.route('/api/v1/staff/qx_order',methods=['POST'],endpoint='qx_order')
@login_required
def qx_order(user):
    orderNo = request.form.get('orderNo') or None
    if orderNo == None:
        return res_msg(201,'参数错误')
    app.logger.info('用户%s 取消了订单  订单号： %s' % (user,orderNo))
    orderItem = Order_list.query.filter_by(orderNo=orderNo).first()
    db.session.delete(orderItem)
    db.session.commit()
    return res_sucss()

#确认收货接口
@app.route('/api/v1/staff/confirm_receipt',methods=['POST'],endpoint='confirm_receipt')
@login_required
def confirm_receipt(user):
    orderNo = request.form.get('orderNo') or None
    if orderNo == None:
        return res_msg(201,'参数错误')
    app.logger.info('用户%s 确认收货了 订单号： %s' % (user,orderNo))
    orderItem = Order_list.query.filter_by(orderNo=orderNo).first()
    orderItem.orderStatus = 3
    db.session.commit()
    return res_sucss()


































